#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    :demo.py
@Author  :keyin
@Time    :2021-01-31 11:16
"""

import cv2
import os
from PyQt5.Qt import *
import numpy as np

img_path = '2.jpg'


# img_path = '3.png'

# color_img = cv2.imread('1.jpg')
# print(color_img.shape)
#
# gray_img = cv2.imread('1.jpg',cv2.IMREAD_GRAYSCALE)
# print(gray_img.shape)

def mySize(img, size):
    """

    :param imgshape: img.shape得到图片的宽和高
    :param size: 在屏幕上最长边的尺寸
    :return:
    """

    y = img.shape[0]
    x = img.shape[1]
    multiples = 1
    if y > size or x > size:
        multiples_y = y // size
        multiples_x = x // size

        if multiples_x > multiples_y:
            multiples = multiples_x + 1
        else:
            multiples = multiples_y + 1

    y = y // multiples
    x = x // multiples

    img_show = cv2.resize(img, (x, y))

    cv2.imshow('image', img_show)

    cv2.waitKey(0)
    cv2.destroyAllWindows()
    return x, y


def findtu(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 转化为灰度图
    blur = cv2.GaussianBlur(gray, (3, 3), 0)  # 用高斯滤波处理原图像降噪
    canny = cv2.Canny(blur, 20, 50)  # 20是最小阈值,50是最大阈值 边缘检测
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    dilation = cv2.dilate(canny, kernel, iterations=1)  # 膨胀一下，来连接边缘
    dilation = cv2.dilate(dilation, kernel, iterations=1)  # 膨胀一下，来连接边缘
    im2, contours, hierarchy = cv2.findContours(dilation,
                                                cv2.RETR_LIST,
                                                cv2.CHAIN_APPROX_SIMPLE)  # 找边框


    adp = img.copy()
    z = 0

    for i in range(len(contours)):
        arclen = cv2.arcLength(contours[i], True)
        epsilon = max(3, int(arclen * 0.01))
        approx = cv2.approxPolyDP(contours[i], epsilon, False)
        area = cv2.contourArea(contours[i])
        rect = cv2.minAreaRect(contours[i])
        box = np.int0(cv2.boxPoints(rect))
        # print(box)
        h = int(rect[1][0]) + 10
        w = int(rect[1][1]) + 10
        if min(h, w) == 0:
            ration = 0
        else:
            ration = max(h, w) / min(h, w)

        col = [(0, 255, 0), (0, 0, 255)]

        if area > 50000 and approx.shape[0] > 4:
        # if area > 50000:
            if z > 0:
                z = 0
            else:
                z = 1
            # cv2.polylines(adp, [approx], True, (0, 255, 0), 20)
            cv2.polylines(adp, [approx], True, col[z], 5)

    # epsilon = 0.1 * cv2.arcLength(contours[0], True)
    # approx = cv2.approxPolyDP(contours[0], epsilon, True)
    # scr = cv2.drawContours(adp, [approx], 0, (0, 0, 255), 20)

    return adp


#     for i in range(len(contours)):
#         cnt =cv2.approxPolyDP(contours[i], 4,True)
#
#     print(cnt)
# #

def find(img):
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 转化为灰度图
    blur = cv2.GaussianBlur(gray, (3, 3), 0)  # 用高斯滤波处理原图像降噪
    canny = cv2.Canny(blur, 0, 80)  # 20是最小阈值,50是最大阈值 边缘检测
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    dilation = cv2.dilate(canny, kernel, iterations=1)  # 膨胀一下，来连接边缘
    dilation = cv2.dilate(dilation, kernel, iterations=1)  # 膨胀一下，来连接边缘
    dilation = cv2.GaussianBlur(dilation, (3, 3), 0)  # 用高斯滤波处理原图像降噪

    im2, contours, hierarchy = cv2.findContours(dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)  # 找边框
    img_draw = cv2.drawContours(im2, contours, -1, (255, 255, 255), 2)
    # print(contours)

    # return img_draw
    # return dilation
    lines = cv2.HoughLinesP(dilation, 1, np.pi / 180, 200, minLineLength=500, maxLineGap=100)

    """
    lines = cv2.HoughLines(dilation,1,np.pi/180,200)

    ipro = 1000
    print(lines)

    for line in lines:
        rho, theta = line[0]
        a = np.cos(theta)
        b = np.sin(theta)
        x0 = a * rho
        y0 = b * rho
        x1 = int(x0+ipro*(-b))
        y1 = int(y0+ipro*(a))
        x2 = int(x0-ipro*(-b))
        y2 = int(y0-ipro*(a))

        cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)
    """
    lines = cv2.HoughLinesP(dilation,1, np.pi/180*5, 200, minLineLength=500, maxLineGap=10)
    print(len(lines))
    for line in lines:
        x1, y1, x2, y2 = line[0]
        cv2.line(img, (x1, y1), (x2, y2), (0, 0, 255), 2)

    return img, dilation


img = cv2.imread(img_path)

# x, y = mySize(img.shape, 1000)

# mySize(img,1000)
cnt, dilation = find(img)

print(type(cnt))

# img, im2= find(img)

mySize(cnt, 1000)
# mySize(im2,1000)

# img_half = cv2.resize(img, (0, 0), fx=0.5, interpolation=cv2.INTER_NEAREST)

# img_add = cv2.copyMakeBorder(img, 50, 50, 0, 0, cv2.BORDER_CONSTANT, value=(0,0,0))

# patch_img = img[20:150, -180:-50]

# cv2.imshow('image', img_show)
# cv2.imshow('img_half', img_half)
# cv2.imshow('img_add', img_add)
# cv2.imshow('patch_img', patch_img)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
